package com.google.code.linescount.func;

import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.regex.Pattern;

import org.eclipse.ui.console.MessageConsoleStream;

class SimpleFileFilter implements FileFilter {

	String pattern;
		
	public SimpleFileFilter() {
		this(".*\\.java");
	}
	
	public SimpleFileFilter(String p) {
		
		if(p==null||p.trim().length()==0) {
			p=".*\\.java";
		}
		pattern=p;
	}
	
	public boolean accept(File arg) {

		String name=arg.getName();
		boolean ret;
		if(arg.isFile() && !Pattern.matches(pattern, name))
			ret=false;
		else
			ret=true;
//		if(arg.isDirectory())
//			System.out.println("<"+name+">");
//		else
//			System.out.println(name+" "+ret);
		return ret;
	}
	
}


public class FileLines {

	public int lines;
	
	public static int getFileLines(String name) {
		File f=new File(name);
		return getFileLines(f);
	}
	
	public static int getFileLines(File file) {
		if(!file.isFile())
			return 0;
		int line=-1;
		LineNumberReader ln;
		try {
			ln=new LineNumberReader(new FileReader(file));
			ln.skip(file.length());
			line=ln.getLineNumber();
			MsgConsoleUtil.printmsg(file.getAbsolutePath()+":"+line);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		return line;
	}
	
	public static int getLines(String dirname) {
		File dir=new File(dirname);
		return getLines(dir);
	}
	
	public static int getLines(File dir) {
		return getLines(dir,"");
	}
	
	public static int getLines(File dir,String filefilter) {
		return getLines(dir,new SimpleFileFilter(filefilter));
	}
	
	public static int getLines(File dir,SimpleFileFilter filefilter) {
		if(dir.isFile())
			return getFileLines(dir);
		if(!dir.exists())
			return 0;
		int len=0;
		System.out.println(filefilter);
		File [] files=dir.listFiles(filefilter);
		for(int i=files.length-1;i>=0;i--) {
			len+=getLines(files[i],filefilter);
		}
		return len;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		String pattern="*.java";
		pattern=pattern.replaceAll("[.]","\\\\.");
		pattern=pattern.replaceAll("[*]", ".*");
		System.out.println(pattern);

	}

}
